﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ExchangeCurrencyRate.Web
{
    public partial class _Default : System.Web.UI.Page
    {
        protected CurrencyRateManager m_CurrencyRateManager = new CurrencyRateManager();

        protected void ConvertMoneyButton_Click(object sender, EventArgs e)
        {
            InvalidCurrencyCodeValidator.IsValid = true;
            if (this.Page.IsValid)
            {
                try
                {
                    if (!this.m_CurrencyRateManager.CheckCurrencyCode(FromCurrencyDropDownList.SelectedValue))
                    {
                        throw new ApplicationException(string.Format("* invalid 'from' currency code: '{0}'", FromCurrencyDropDownList.SelectedValue));
                    }
                    else if (!this.m_CurrencyRateManager.CheckCurrencyCode(ToCurrencyDropDownList.SelectedValue))
                    {
                        throw new ApplicationException(string.Format("* invalid 'to' currency code: '{0}'", ToCurrencyDropDownList.SelectedValue));
                    }
                    ResultValueLabel.Text = this.m_CurrencyRateManager.Exchange(
                        FromCurrencyDropDownList.SelectedValue,
                        ToCurrencyDropDownList.SelectedValue, decimal.Parse(ValueTextBox.Text))
                        .ToString();
                }
                catch (FormatException)
                {
                    InvalidCurrencyCodeValidator.IsValid = false;
                    InvalidCurrencyCodeValidator.ErrorMessage = string.Format("* invalid money value '{0}'", ValueTextBox.Text);
                }
                catch (ApplicationException ex)
                {
                    InvalidCurrencyCodeValidator.IsValid = false;
                    InvalidCurrencyCodeValidator.ErrorMessage = ex.Message;
                }
            }
        }
    }
}
